const query = require('../queryEngine/index.js');
const tool = require('../common/index.js');

module.exports = {
    'GET /list': async (ctx, next) => {
        ctx.response.type = 'application/json';
        await query.list({where: {...tool.parseUrl(ctx.request.url),flag:0}}).then(res=>{
            if (res.length==0){
                ctx.response.status = 404;
                ctx.response.message = 'not found article'
            }else{
                ctx.response.body = res;
            }
        })
    },
    'GET /addCount': async (ctx, next) => {
        ctx.response.type = 'application/json';
        ctx.response.body = await query.addReadCount({where: tool.parseUrl(ctx.request.url)})
    },
    'POST /addArticle': async (ctx, next) => {
        ctx.request.type = 'application/x-www-form-urlencoded';
        await query.addArticle(ctx.request.body).then(() => {
            ctx.response.body = {
                errorCode: 0,
                errorMsg: '成功'
            };
        }).catch((err) => {
            ctx.response.status = 484;
            ctx.response.message = err;
        });
    },
    'DELETE /deleteArticle': async (ctx, next) => {
        ctx.response.type = 'application/x-www-form-urlencoded';
        await query.deleteArticle( {where: {id: Number(tool.parseUrl(ctx.request.url).id)}}).then((res) => {
            ctx.response.body = {
                errorCode: 0,
                errorMsg: '成功'
            };
        }).catch(err => {
            ctx.response.status = 487;
            ctx.response.message = err.name;
        });
    },
    'POST /updateArticle': async (ctx, next) => {
        ctx.request.type = 'application/x-www-form-urlencoded';
        let obj = ctx.request.body;
        let id = obj.id;
        delete obj.id;
        await query.updateArticle(obj, {where: {id: id}}).then(() => {
            ctx.response.body = {
                errorCode: 0,
                errorMsg: '成功'
            };
        }).catch((err) => {
            ctx.response.status = 485;
            ctx.response.message = err;
        });
    },
    'GET /lastArticles':async (ctx,next)=>{
        ctx.response.type = 'application/json';
        ctx.response.body = await query.lastArticles(Number(tool.parseUrl(ctx.request.url).number))
    }
};